package com.pf.common.helper;

import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryListener;
import com.pf.mapper.entity.JobInfo;
import com.pf.utils.GuavaRetryingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * 任务重试
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/8/14
 */
@Slf4j
@Component
public class ScheduledJobRetryHelper {


    public <T> T retryExecuteJob(JobInfo jobInfo, Callable callable, Class<? extends Throwable> exceptionClazz, Class<T> resultClazz) {
        return GuavaRetryingUtils.retry(jobInfo.getRetryNums(), 1, new JobRetryListener(jobInfo.getJobId()), callable, exceptionClazz, resultClazz);
    }


    /**
     * 组装 logInfo信息
     *
     * @param jobId
     * @param jobExecuteStatus
     * @param errorLog
     * @return
     */
//    private LogInfo buildLogInfo(String jobId, JobExecuteStatusEnum jobExecuteStatus, String errorLog) {
//        return LogInfo.builder()
//                .jobId(jobId)
//                .executeStatus(jobExecuteStatus.getCode())
//                .executeDate(new Date())
//                .errorLog(errorLog)
//                .build();
//    }


    /**
     * 自定义监听器
     */
    private class JobRetryListener implements RetryListener {

        private String jobId;

        public JobRetryListener(String jobId) {
            this.jobId = jobId;
        }

        @Override
        public <V> void onRetry(Attempt<V> attempt) {
            log.info(">>>>> JobRetryListener - onRetry attemptNumber={}", attempt.getAttemptNumber());
            if (attempt.hasException()) {
                // 做日志记录
                log.info(">>>>> JobRetryListener - onRetry exception={}", attempt.getExceptionCause());
            } else {
                log.info(">>>>> JobRetryListener - onRetry success");
            }
            if (attempt.hasResult()) {
                if (attempt.getResult() == null) {
                    log.info(">>>>> JobRetryListener - onRetry 返回结果为空！");
                } else {
                    log.info(">>>>> JobRetryListener - onRetry result data ={}", attempt.getResult());
                }
            }
        }
    }
}
